#coding:utf-8
import sys,os,json,random,commands,queue_task,time,threading
sys.path.append('/home/cheungssh/bin')
sys.path.append('/home/cheungssh/mysite/mysite/cheungssh')
from django.core.cache import cache
REDIS=cache.master_client
import zipfile
import re
import os
reload(sys)
sys.setdefaultencoding('utf8')
from django.contrib.auth.models import User,Group
from django.http import  HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from Return_http import ajax_http
from login_check import login_check
from models import FileList
from action import *
from models import *




@ajax_http #####用来处理ajax的跨域请求头消息
def whoami(request):
	R=request
	info={"status":True,"content":""}
	username=request.user.username
	if not R.user.is_authenticated():
		return {"status":"login"}
	info["date"]=time.strftime('%Y-%m-%d',time.localtime()),
	info["username"]=username
	return info
	
@ajax_http
def cheungssh_login(request):
	info={"status":False,"content":""}
	if request.method=="POST":
		username = request.POST.get("username", '非法用户名')
		password = request.POST.get("password", False)
		user=authenticate(username=username,password=password)
		if user is not None:
			if user.is_active:
				login(request,user)
				request.session["username"]=username
				info["status"]=True
			else:
				
				info["content"]="用户状态无效"
		else:
			info["content"]="用户名或密码错误"
		################写入登录记录
	else:
		info["content"]="No Get"
        return info
@login_check
@ajax_http
def upload_file(R):
	info={"content":[],"status":True}
	username=R.user.username
	current_time=int(time.time())
	if R.method=="POST":
		t=R.FILES.get("file")
		filename=t.name
		tmp=random.randint(11111111111,99999999999)
		path1="/cheungssh/static/download/{tmp}_{filename}".format(tmp=tmp,filename=filename)
		path2="/home/cheungssh/web/cheungssh/static/download/{tmp}_{filename}".format(tmp=tmp,filename=filename)
		with open(path2,"wb") as f:
			f.write(t.read())
		dest_dir="/tmp/{tmp}".format(tmp=tmp)
		dest_file="{dest_dir}/{filename}".format(dest_dir=dest_dir,filename=filename)
		cmd="""mkdir -p {dest_dir} && cp {source_file} {dest_file} && cd {dest_dir} && unzip {dest_file} >/dev/null && find  ./ -type f -name 'data.mdb'""".format(
			source_file=path2,
			dest_file=dest_file,
			dest_dir=dest_dir,
		)
		m=commands.getstatusoutput(cmd)
		if not m[0]==0:
			return {"content":"系统错误，请联系管理员！","status":False}
		if len(m[1].split())>1:
			print m[1],33
			return {"content":"您上传的文件中存在多个mdb文件，您只能上传一个data.mdb文件！","status":False}
		XX=FileList(
			username=username,
			path=path1,	
			date=current_time,
			filename=filename,
		)
		XX.save()
		""" 本部分统计压缩包内的目录数量"""
		cmd="""cd {dest_dir} && find  ./ -type d|wc -l""".format(
			dest_dir=dest_dir,
		)
		k=commands.getstatusoutput(cmd)
		folder_amount=re.search("[0-9]+",k[1]).group()
		folder_amount=int(folder_amount)-1
		cmd="""cd {dest_dir} && find  ./ -type f|wc -l""".format(
			dest_dir=dest_dir,
		)
		k=commands.getstatusoutput(cmd)
		file_amount=re.search("[0-9]+",k[1]).group()
		file_amount=int(file_amount)-1



		mdb_file=m[1]
		mdb_file=os.path.join(dest_dir,mdb_file) # mdb文件的路径
		fileid=XX.id
		record_amount=0 # 总的入库记录
		try:
			cur=go(mdb_file)
			data=C_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				C(*m).save()
				record_amount+=1
			print "已经录入C表"
		except Exception,e:
			print "不能录入C表"
		try:
			m=[]
			data=H_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(str(y).strip("\x00")) for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				print m
				tt=H(*m).save()
				record_amount+=1
				print "已录入H"
		except Exception,e:
			print "不能录入H表",e
		try:
			data=XZQ_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				XZQ(*m).save()
				record_amount+=1
			print "已经录入XZQ表"
		except Exception,e:
			print "不能录入XZQ表"
		try:
			data=DJQ_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				DJQ(*m).save()
				record_amount+=1
			print "已经录入DJQ表"
		except Exception,e:
			print "不能录入DJQ表"

		try:
			data=ZDJBXX_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				ZDJBXX(*m).save()
				record_amount+=1
			print "已经录入ZDJBXX表"
		except Exception,e:
			print "不能录入ZDJBXX表"

		try:
			data=JZX_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				JZX(*m).save()
				record_amount+=1
			print "已经录入JZX表"
		except Exception,e:
			print "不能录入JZX表"

		try:
			data=JZD_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				JZD(*m).save()
				record_amount+=1
			print "已经录入JZD表"
		except Exception,e:
			print "不能录入JZD表"

		try:
			data=ZRZ_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				ZRZ(*m).save()
				record_amount+=1
			print "已经录入ZRZ表"
		except Exception,e:
			print "不能录入ZRZ表"

		try:
			data=GZW_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				GZW(*m).save()
				record_amount+=1
			print "已经录入GZW表"
		except Exception,e:
			print "不能录入GZW表"

		try:
			data=QLR_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				QLR(*m).save()
				record_amount+=1
			print "已经录入QLR表"
		except Exception,e:
			print "不能录入QLR表"


		try:
			data=LJZ_T(cur)
			for i in data:
				_id=random.randint(100,999999999)
				m=[str(y).strip("\x00") for y in i]
				m.insert(0,current_time)
				m.insert(0,username)
				m.insert(0,fileid)
				m.insert(0,_id)
				LJZ(*m).save()
				record_amount+=1
			print "已经录入LJZ表"
		except Exception,e:
			print "不能录入LJZ表"
		FileList.objects.filter(id=XX.id).update(
			file_amount=file_amount,
			folder_amount=folder_amount,
			record_amount=record_amount,
		)



	elif R.method=="GET":
		if R.user.is_superuser:
			t=FileList.objects.all()
		else:
			t=FileList.objects.filter(username=username)
		for i in t:
			info["content"].append({
				"id":i.id,
				"username":i.username,
				"filename":i.filename,
				"path":i.path,
				"date":time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(i.date)),
				"folder_amount":i.folder_amount,
				"file_amount":i.file_amount,
				"record_amount":i.record_amount,
				})
	return info
@login_check
@ajax_http
def table(R):
	info={"status":True,"content":[],"title":[]}
	fileid=R.GET.get("fileid")
	table=R.GET.get("table")
	start_date=R.GET.get("start_date")
	end_date=R.GET.get("end_date")
	if not start_date is None:
		start_date= start_date+" 00:00:00"
		end_date= end_date+" 23:59:59"
		start_date=int(time.mktime(time.strptime(start_date,"%Y-%m-%d %H:%M:%S")) )
		end_date=int(time.mktime(time.strptime(end_date,"%Y-%m-%d %H:%M:%S")) )
	else:
		start_date=0
		end_date=2645172595
	if table=="H":
		if not fileid==None:
			m=H.objects.filter(fileid=fileid)
		else:
			m=H.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="C":
		if not fileid==None:
			m=C.objects.filter(fileid=fileid)
		else:
			m=C.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="XZQ":
		if not fileid==None:
			m=XZQ.objects.filter(fileid=fileid)
		else:
			m=XZQ.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="DJQ":
		if not fileid==None:
			m=DJQ.objects.filter(fileid=fileid)
		else:
			m=DJQ.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="DJZQ":
		if not fileid==None:
			m=DJZQ.objects.filter(fileid=fileid)
		else:
			m=DJZQ.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="ZDJBXX":
		if not fileid==None:
			m=ZDJBXX.objects.filter(fileid=fileid)
		else:
			m=ZDJBXX.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="JZX":
		if not fileid==None:
			m=JZX.objects.filter(fileid=fileid)
		else:
			m=JZX.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="JZD":
		if not fileid==None:
			m=JZD.objects.filter(fileid=fileid)
		else:
			m=JZD.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="ZRZ":
		if not fileid==None:
			m=ZRZ.objects.filter(fileid=fileid)
		else:
			m=ZRZ.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="GZW":
		if not fileid==None:
			m=GZW.objects.filter(fileid=fileid)
		else:
			m=GZW.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="QLR":
		if not fileid==None:
			m=QLR.objects.filter(fileid=fileid)
		else:
			m=QLR.objects.filter(date__gt=start_date,date__lte=end_date)
	elif table=="LJZ":
		if not fileid==None:
			m=LJZ.objects.filter(fileid=fileid)
		else:
			m=LJZ.objects.filter(date__gt=start_date,date__lte=end_date)
	for i in m:
		data=i.__dict__.items()
		_data=[]
		for key,value in data:
			if key=="_state":continue
			if key=="date":
				_data.append(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(value)))
			else:
				_data.append(value)
			if not key in info["title"]:info["title"].append(key)
		info["content"].append(_data)
	info["content"]=info["content"][:500]
	return info
